<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '任务分类',
  },
}
</route>
<template>
  <view class="categories-page">
    <!-- 自定义导航栏 -->
    <view
      class="custom-nav-bar bg-white p-4 border-b border-gray-200 flex justify-between items-center"
      :style="{ paddingTop: safeAreaInsets?.top + 'px' }"
    >
      <view class="flex items-center">
        <text class="i-fa-solid:chevron-left text-lg mr-2" @click="goBack"></text>
        <text class="text-xl font-semibold">任务分类</text>
      </view>
      <view class="text-blue-500" @click="showAddCategoryModal">
        <text class="i-fa-solid:plus"></text>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 分类列表 -->
    <view v-else class="categories-container">
      <view v-if="categories.length === 0" class="empty-state">
        <text class="empty-text">暂无分类</text>
        <text class="empty-subtext">点击右上角添加新分类</text>
      </view>
      <view v-else class="category-list">
        <view
          v-for="category in categories"
          :key="category.id"
          class="category-item"
          @click="handleCategoryClick(category)"
        >
          <view class="category-info">
            <view 
              class="category-icon" 
              :style="{ color: category.color || '#8e8e93' }"
            >
              <text :class="[category.icon || 'i-fa-solid:tag']"></text>
            </view>
            <view class="category-name-container">
              <text class="category-name">{{ category.name }}</text>
              <view v-if="category.isDefault" class="default-badge">
                <text>默认</text>
              </view>
            </view>
          </view>
          <view class="category-task-count">
            <text>{{ categoryTaskCounts[category.id] || 0 }} 个任务</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 添加分类弹窗 -->
    <view v-if="showAddModal" class="modal-overlay" @click="showAddModal = false">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">{{ editingCategory ? '编辑分类' : '添加分类' }}</text>
          <text class="modal-close" @click="showAddModal = false">
            <text class="i-fa-solid:times"></text>
          </text>
        </view>
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">名称</text>
            <input
              type="text"
              class="form-input"
              placeholder="请输入分类名称"
              v-model="newCategory.name"
            />
          </view>
          <view class="form-item">
            <text class="form-label">图标</text>
            <view class="icon-selector" @click="showIconSelector = true">
              <text :class="[newCategory.icon || 'i-fa-solid:tag']"></text>
              <text class="ml-2">{{ newCategory.icon ? '已选择' : '选择图标' }}</text>
            </view>
          </view>
          <view class="form-item">
            <text class="form-label">颜色</text>
            <view class="color-selector">
              <view
                v-for="color in colorOptions"
                :key="color.value"
                class="color-option"
                :style="{ backgroundColor: color.value }"
                :class="{ active: newCategory.color === color.value }"
                @click="selectColor(color.value)"
              ></view>
            </view>
          </view>
          <view class="form-item" v-if="!editingCategory || !editingCategory.isSystem">
            <text class="form-label">设为默认</text>
            <switch
              :checked="newCategory.isDefault"
              @change="toggleDefault"
              color="#007aff"
            />
          </view>
        </view>
        <view class="modal-footer">
          <button class="modal-button cancel" @click="showAddModal = false">取消</button>
          <button class="modal-button confirm" @click="saveCategory">
            {{ editingCategory ? '保存' : '添加' }}
          </button>
        </view>
      </view>
    </view>

    <!-- 图标选择器弹窗 -->
    <view v-if="showIconSelector" class="modal-overlay" @click="showIconSelector = false">
      <view class="modal-content icon-selector-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">选择图标</text>
          <text class="modal-close" @click="showIconSelector = false">
            <text class="i-fa-solid:times"></text>
          </text>
        </view>
        <view class="modal-body">
          <view class="icon-grid">
            <view
              v-for="icon in iconOptions"
              :key="icon"
              class="icon-option"
              :class="{ active: newCategory.icon === icon }"
              @click="selectIcon(icon)"
            >
              <text :class="[icon]"></text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 分类操作菜单 -->
    <view v-if="showCategoryMenu" class="modal-overlay" @click="showCategoryMenu = false">
      <view class="action-menu" @click.stop>
        <view class="action-item" @click="editCategory">
          <text class="i-fa-solid:edit mr-2"></text>
          <text>编辑分类</text>
        </view>
        <view
          v-if="!selectedCategory?.isSystem && !selectedCategory?.isDefault"
          class="action-item"
          @click="setAsDefault"
        >
          <text class="i-fa-solid:star mr-2"></text>
          <text>设为默认</text>
        </view>
        <view class="action-item" @click="viewCategoryTasks">
          <text class="i-fa-solid:list mr-2"></text>
          <text>查看相关任务</text>
        </view>
        <view
          v-if="!selectedCategory?.isSystem"
          class="action-item delete"
          @click="confirmDeleteCategory"
        >
          <text class="i-fa-solid:trash-alt mr-2"></text>
          <text>删除分类</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
defineOptions({
  name: 'TaskCategories',
})

import { ref, onMounted } from 'vue'
import { taskService } from '@/services/task-service'
import type { Category } from '@/services/database'

// 获取安全区域
const { safeAreaInsets } = uni.getSystemInfoSync()

// 数据状态
const loading = ref(true)
const categories = ref<Category[]>([])
const categoryTaskCounts = ref<Record<string, number>>({})

// 弹窗状态
const showAddModal = ref(false)
const showIconSelector = ref(false)
const showCategoryMenu = ref(false)

// 新分类数据
const newCategory = ref({
  name: '',
  icon: '',
  color: '#4a6ee0',
  isDefault: false
})

// 当前选中的分类
const selectedCategory = ref<Category | null>(null)
// 是否处于编辑状态
const editingCategory = ref<Category | null>(null)

// 颜色选项
const colorOptions = [
  { name: '蓝色', value: '#4a6ee0' },
  { name: '红色', value: '#ff3b30' },
  { name: '橙色', value: '#ff9500' },
  { name: '黄色', value: '#ffcc00' },
  { name: '绿色', value: '#34c759' },
  { name: '青色', value: '#5ac8fa' },
  { name: '紫色', value: '#af52de' },
  { name: '粉色', value: '#ff2d55' },
  { name: '灰色', value: '#8e8e93' }
]

// 图标选项
const iconOptions = [
  'i-fa-solid:briefcase',
  'i-fa-solid:home',
  'i-fa-solid:school',
  'i-fa-solid:utensils',
  'i-fa-solid:dumbbell',
  'i-fa-solid:book',
  'i-fa-solid:shopping-cart',
  'i-fa-solid:plane',
  'i-fa-solid:heart',
  'i-fa-solid:gamepad',
  'i-fa-solid:music',
  'i-fa-solid:film',
  'i-fa-solid:star',
  'i-fa-solid:coffee',
  'i-fa-solid:chart-line',
  'i-fa-solid:tag'
]

/**
 * 加载分类列表
 */
const loadCategories = async () => {
  loading.value = true
  try {
    // 获取所有任务分类
    categories.value = await taskService.getTaskCategories()
    
    // 获取每个分类的任务数量
    categoryTaskCounts.value = await taskService.getTaskCountByCategory()
    
  } catch (error) {
    console.error('加载分类失败:', error)
    uni.showToast({
      title: '加载分类失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

/**
 * 返回上一页
 */
const goBack = () => {
  uni.navigateBack()
}

/**
 * 显示添加分类弹窗
 */
const showAddCategoryModal = () => {
  // 重置表单
  newCategory.value = {
    name: '',
    icon: '',
    color: '#4a6ee0',
    isDefault: false
  }
  editingCategory.value = null
  showAddModal.value = true
}

/**
 * 选择颜色
 */
const selectColor = (color: string) => {
  newCategory.value.color = color
}

/**
 * 选择图标
 */
const selectIcon = (icon: string) => {
  newCategory.value.icon = icon
  showIconSelector.value = false
}

/**
 * 切换默认状态
 */
const toggleDefault = (event: any) => {
  newCategory.value.isDefault = event.detail.value
}

/**
 * 保存分类
 */
const saveCategory = async () => {
  // 验证名称
  if (!newCategory.value.name.trim()) {
    uni.showToast({
      title: '请输入分类名称',
      icon: 'none'
    })
    return
  }

  try {
    let success = false
    
    if (editingCategory.value) {
      // 更新分类
      success = await taskService.updateTaskCategory(
        editingCategory.value.id,
        newCategory.value.name,
        newCategory.value.icon,
        newCategory.value.color,
        newCategory.value.isDefault
      )
    } else {
      // 创建新分类
      success = await taskService.createTaskCategory(
        newCategory.value.name,
        newCategory.value.icon,
        newCategory.value.color,
        newCategory.value.isDefault
      )
    }

    if (success) {
      uni.showToast({
        title: editingCategory.value ? '分类已更新' : '分类已创建',
        icon: 'success'
      })
      showAddModal.value = false
      // 重新加载分类
      loadCategories()
    } else {
      throw new Error('保存失败')
    }
  } catch (error) {
    console.error('保存分类失败:', error)
    uni.showToast({
      title: '保存失败',
      icon: 'none'
    })
  }
}

/**
 * 处理分类点击事件
 */
const handleCategoryClick = (category: Category) => {
  selectedCategory.value = category
  showCategoryMenu.value = true
}

/**
 * 编辑分类
 */
const editCategory = () => {
  if (!selectedCategory.value) return
  
  editingCategory.value = selectedCategory.value
  newCategory.value = {
    name: selectedCategory.value.name,
    icon: selectedCategory.value.icon || '',
    color: selectedCategory.value.color || '#4a6ee0',
    isDefault: selectedCategory.value.isDefault === 1
  }
  
  showCategoryMenu.value = false
  showAddModal.value = true
}

/**
 * 设置为默认分类
 */
const setAsDefault = async () => {
  if (!selectedCategory.value) return
  
  try {
    const success = await taskService.updateTaskCategory(
      selectedCategory.value.id,
      selectedCategory.value.name,
      selectedCategory.value.icon,
      selectedCategory.value.color,
      true
    )
    
    if (success) {
      uni.showToast({
        title: '已设为默认分类',
        icon: 'success'
      })
      showCategoryMenu.value = false
      // 重新加载分类
      loadCategories()
    } else {
      throw new Error('设置失败')
    }
  } catch (error) {
    console.error('设置默认分类失败:', error)
    uni.showToast({
      title: '设置失败',
      icon: 'none'
    })
  }
}

/**
 * 查看分类任务
 */
const viewCategoryTasks = () => {
  if (!selectedCategory.value) return
  
  uni.navigateTo({
    url: `/pages/task/list?categoryId=${selectedCategory.value.id}&categoryName=${encodeURIComponent(selectedCategory.value.name)}`
  })
  
  showCategoryMenu.value = false
}

/**
 * 确认删除分类
 */
const confirmDeleteCategory = () => {
  if (!selectedCategory.value || selectedCategory.value.isSystem) return
  
  uni.showModal({
    title: '删除分类',
    content: '确定要删除该分类吗？相关任务将移至默认分类。',
    success: async (res) => {
      if (res.confirm) {
        try {
          const success = await taskService.deleteTaskCategory(selectedCategory.value!.id)
          
          if (success) {
            uni.showToast({
              title: '分类已删除',
              icon: 'success'
            })
            showCategoryMenu.value = false
            // 重新加载分类
            loadCategories()
          } else {
            throw new Error('删除失败')
          }
        } catch (error) {
          console.error('删除分类失败:', error)
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 初始加载
onMounted(() => {
  loadCategories()
})
</script>

<style lang="scss">
.categories-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f2f2f7;
}

.loading-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  width: 30px;
  height: 30px;
  border: 3px solid rgba(0, 122, 255, 0.1);
  border-top-color: #007aff;
  border-radius: 50%;
  animation: spin 1s infinite linear;
}

.loading-text {
  margin-top: 12px;
  font-size: 14px;
  color: #8e8e93;
}

.categories-container {
  flex: 1;
  padding: 16px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.empty-text {
  font-size: 18px;
  font-weight: 500;
  color: #8e8e93;
  margin-bottom: 8px;
}

.empty-subtext {
  font-size: 14px;
  color: #8e8e93;
}

.category-list {
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
}

.category-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #e5e5ea;
}

.category-item:last-child {
  border-bottom: none;
}

.category-info {
  display: flex;
  align-items: center;
}

.category-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  margin-right: 12px;
  font-size: 18px;
}

.category-name-container {
  display: flex;
  align-items: center;
}

.category-name {
  font-size: 16px;
  color: #000;
}

.default-badge {
  margin-left: 8px;
  font-size: 12px;
  color: #007aff;
  background-color: rgba(0, 122, 255, 0.1);
  padding: 2px 6px;
  border-radius: 8px;
}

.category-task-count {
  font-size: 14px;
  color: #8e8e93;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.modal-content {
  width: 80%;
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #e5e5ea;
}

.modal-title {
  font-size: 18px;
  font-weight: 500;
  color: #000;
}

.modal-close {
  font-size: 16px;
  color: #8e8e93;
}

.modal-body {
  padding: 16px;
}

.form-item {
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-label {
  font-size: 14px;
  color: #8e8e93;
  margin-bottom: 8px;
}

.form-input {
  height: 44px;
  padding: 0 12px;
  border: 1px solid #e5e5ea;
  border-radius: 8px;
  font-size: 16px;
}

.color-selector {
  display: flex;
  flex-wrap: wrap;
  margin: -4px;
}

.color-option {
  width: 32px;
  height: 32px;
  border-radius: 16px;
  margin: 4px;
  border: 2px solid transparent;
}

.color-option.active {
  border-color: #007aff;
}

.icon-selector {
  height: 44px;
  border: 1px solid #e5e5ea;
  border-radius: 8px;
  display: flex;
  align-items: center;
  padding: 0 12px;
  font-size: 16px;
}

.icon-selector-modal {
  width: 90%;
  max-height: 80%;
}

.icon-grid {
  display: flex;
  flex-wrap: wrap;
  margin: -4px;
}

.icon-option {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 4px;
  border-radius: 8px;
  font-size: 20px;
  background-color: #f2f2f7;
}

.icon-option.active {
  background-color: #007aff;
  color: white;
}

.modal-footer {
  display: flex;
  border-top: 1px solid #e5e5ea;
}

.modal-button {
  flex: 1;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  background-color: transparent;
  border: none;
}

.modal-button.cancel {
  color: #8e8e93;
  border-right: 1px solid #e5e5ea;
}

.modal-button.confirm {
  color: #007aff;
}

.action-menu {
  width: 80%;
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
}

.action-item {
  height: 50px;
  display: flex;
  align-items: center;
  padding: 0 16px;
  border-bottom: 1px solid #e5e5ea;
  font-size: 16px;
}

.action-item:last-child {
  border-bottom: none;
}

.action-item.delete {
  color: #ff3b30;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style> 